package com.taotao.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.taotao.mapper.TbContentMapper;
import com.taotao.pojo.*;
import com.taotao.service.ContentService;
import com.taotao.util.HttpClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * Created by caiyinli on 2018/8/24.
 */
@Service
public class ContentServiceImpl implements ContentService{

    @Autowired
    private TbContentMapper tbContentMapper;

    @Value("${REST_BASE_URL}")
    private String REST_BASE_URL;

    @Value("${REST_CONTENT_SYNC_URL}")
    private String REST_CONTENT_SYNC_URL;

    @Override
    public EasyUIResult getContentList(int page, int rows,Long categoryId) {
        TbContentExample tbContentExample = new TbContentExample();
        TbContentExample.Criteria criteria = tbContentExample.createCriteria();
        criteria.andCategoryIdEqualTo(categoryId);
        PageHelper.startPage(page,rows);
        List<TbContent> tbContents = tbContentMapper.selectByExample(tbContentExample);
        Page<TbContent> pageInfo = (Page<TbContent>)tbContents;
        EasyUIResult easyUIResult = new EasyUIResult();
        easyUIResult.setRows(tbContents);
        easyUIResult.setTotal((int) pageInfo.getTotal());
        return easyUIResult;
    }

    @Override
    public TaotaoResult insertContent(TbContent content) {
        content.setCreated(new Date());
        content.setUpdated(new Date());
        tbContentMapper.insertSelective(content);

        //添加缓存同步逻辑,即清除缓存
        try {
            HttpClientUtil.doGet(REST_BASE_URL+REST_CONTENT_SYNC_URL+content.getCategoryId());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return TaotaoResult.ok();
    }
}
